/*
 * @Author: jipeng.Li
 * @Date: 2020-01-14  15:32:52.91
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-19 14:42:37
 * @Description: 司机端运单详情
 */

import React, { Component } from 'react';
import {
  Image,
  Linking,
  NativeModules,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  fontColorCoffee,
  fontColorSecDeepGray,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  splitLineColorLightGray,
  fontColorDeepRed,
  screenWidth,
} from '@/styles';
import { msg, Button, _ } from '@/common';
import api from '@/api';
import { iconLeftWhite, iconCirclePhoneGray } from '@/images';
import {
  TypeAssemble,
  WaybillLine,
  DriverInfoCard,
  XMImageViewer,
} from '@/components';
import baseConfig from '@/config/baseConfig';

const { fileUrl } = baseConfig;
const { Submit } = Button;

export default class DriverOrderDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      details: null,
      modalVisible: false,
      imageSources: [],
      unitOptionsMap: {},
      truckTypeDict: [],
      plat: '', // 1  货主端   2车主端  3 司机端
      businessNo: '',
      isRefreshList: false, // 返回是否刷新运单列表
      routerFrom: 'driverMain',
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { businessNo, plat, routerFrom } = params;
    this.getUnitList();
    this.setState({ plat, businessNo, routerFrom });
    this.info(businessNo, plat);
    // this.fetchUnitList();
  }

  render() {
    const { details, modalVisible, imageSources, plat } = this.state;
    return (
      <SafeAreaView style={style.container}>
        <ScrollView style={{ flex: 1 }}>
          {details && (
            <View
              style={[
                this.checkStyle() && style.scrollMargin,
                { paddingHorizontal: px2dp(20) },
              ]}
            >
              {/* plat   1  货主端   2车主端  3 司机端 */}
              {this.waybillView()}
              {/* 货物类型 */}
              {this.goodsTypeView()}
              {/* 备注信息 */}
              {this.remakeView()}
              {/* 装卸信息 */}
              {this.waybillRouteView()}
              {/* 货主信息 */}
              {this.cargOwnerInfo()}
              {/* 回单信息 */}
              {this.receiptInfoView()}
              {/* 图片查看 */}
              <XMImageViewer
                leftBackIcon={iconLeftWhite}
                showViewModal={() => this.setState({ modalVisible: false })}
                previewModal={modalVisible}
                images={imageSources}
              />
            </View>
          )}
        </ScrollView>
        {/* 底部按钮 */}
        {this.checkBtn(
          details && details.transportStatus,
          details && details.loadingStatus,
          details && details.needReceipt,
          details && details.status,
          details && details.orderType,
        )}
      </SafeAreaView>
    );
  }

  _handleBack = () => {
    msg.emit('router: back');
    return true;
  };

  // 获取单位
  getUnitList = () => {
    api.supply.unitList().then((res) => {
      let unitOptionsMap = {};
      res.data.forEach((item) => {
        unitOptionsMap[item.code] = item.name;
      });
      this.setState({ unitOptionsMap });
    });
  };

  // 提交数据api //上传发货单，收货单
  submitUploadTick = (transportNo, guideData) => {
    // 拼接参数
    let params = {
      id: guideData.id,
      transportNo: transportNo,
      details: [],
    };
    api.supply.uploadTick(params).then((res) => {
      if (res.success) {
        msg.emit('app:tip', { text: '提交成功' });
        this.info(transportNo, this.state.plat);
        this.setState({ isRefreshList: true });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 详情跳转回单
  toReceipt() {
    const { details, plat, routerFrom } = this.state;
    if (plat === 3 && details.transportStatus === 1) {
      // 装货、卸货回单上传
      api.supply
        .getUploadTick({ transportNo: details.transports[0].transportNo })
        .then((res) => {
          if (res.data.needReceipt == 2) {
            this.submitUploadTick(details.transports[0].transportNo, res.data);
          } else {
            msg.emit('router: goToNext', {
              routeName: 'ReceiptUpload',
              routerFrom: routerFrom,
              data: details,
              transportNo: details.transports[0].transportNo,
              guideData: res.data,
            });
          }
        });
    } else {
      // 回单编辑
      msg.emit('router: goToNext', {
        routeName: 'ReceiptEdit',
        routerFrom: routerFrom,
        data: details,
        transportNo: details.transports[0].transportNo,
      });
    }
  }

  checkStyle = () => {
    const { details } = this.state;
    const { transportStatus, needReceipt, status } = details;
    if (transportStatus === 1) {
      return true;
    }
    if (transportStatus === 2) {
      // 显示修改回单按钮
      if (needReceipt == 1 && status != 4 && status != 5) {
        return true;
      }
      // 无底部按钮
      return false;
    }
  };

  checkBtn = (
    transportStatus,
    loadingStatus,
    needReceipt,
    status,
    orderType,
  ) => {
    if (transportStatus === 1) {
      if (loadingStatus === 1) {
        // 显示装货按钮
        return (
          <View style={style.botTab}>
            <View style={{ flex: 1 }} />
            <Submit
              text='装货'
              boxStyle={{
                width: px2dp(328),
                height: px2dp(80),
                borderRadius: px2dp(40),
                borderColor: fontColorCoffee,
                borderWidth: px2dp(1),
                backgroundColor: fontColorCoffee,
                marginRight: px2dp(20),
              }}
              btnTextStyle={{
                color: mainBgColorWhite,
                fontSize: px2dp(32),
              }}
              onClick={() => {
                this.toReceipt();
              }}
            />
          </View>
        );
      }
      if (loadingStatus === 2) {
        // 显示卸货按钮
        return (
          <View style={style.botTab}>
            <View style={{ flex: 1 }} />
            <Submit
              text='卸货'
              boxStyle={{
                width: px2dp(328),
                height: px2dp(80),
                borderRadius: px2dp(40),
                borderColor: fontColorCoffee,
                borderWidth: px2dp(1),
                backgroundColor: fontColorCoffee,
                marginRight: px2dp(20),
              }}
              btnTextStyle={{
                color: mainBgColorWhite,
                fontSize: px2dp(32),
              }}
              onClick={() => {
                this.toReceipt();
              }}
            />
          </View>
        );
      }
    } else if (transportStatus === 2) {
      // 显示修改回单按钮
      if (needReceipt == 1 && status != 4 && status != 5) {
        return (
          <View style={style.botTab}>
            <View style={{ flex: 1 }} />
            {orderType == 2 && (
              <Submit
                text='再来一单'
                boxStyle={{
                  width: px2dp(328),
                  height: px2dp(80),
                  borderRadius: px2dp(40),
                  borderColor: '#CDCCC9',
                  borderWidth: px2dp(1),
                  backgroundColor: 'white',
                  marginRight: px2dp(20),
                }}
                btnTextStyle={{
                  color: '#999796',
                  fontSize: px2dp(32),
                }}
                onClick={() => {
                  this.driverNextWaybill();
                }}
              />
            )}
            <Submit
              text='修改回单'
              boxStyle={{
                width: px2dp(328),
                height: px2dp(80),
                borderRadius: px2dp(40),
                borderColor: fontColorCoffee,
                borderWidth: px2dp(1),
                backgroundColor: fontColorCoffee,
                marginRight: px2dp(20),
              }}
              btnTextStyle={{
                color: mainBgColorWhite,
                fontSize: px2dp(32),
              }}
              onClick={() => {
                this.toReceipt();
              }}
            />
          </View>
        );
      }
      if (orderType == 2) {
        return (
          <View style={style.botTab}>
            <View style={{ flex: 1 }} />

            <Submit
              text='再来一单'
              boxStyle={{
                width: px2dp(328),
                height: px2dp(80),
                borderRadius: px2dp(40),
                borderColor: '#CDCCC9',
                borderWidth: px2dp(1),
                backgroundColor: 'white',
                marginRight: px2dp(20),
              }}
              btnTextStyle={{
                color: '#999796',
                fontSize: px2dp(32),
              }}
              onClick={() => {
                this.driverNextWaybill();
              }}
            />
          </View>
        );
      }
      return <View />;
    }
  };

  // 再来一单
  driverNextWaybill = () => {
    const { details } = this.state;
    api.supply
      .driverNextWaybill({ transportNo: details.transports[0].transportNo })
      .then((res) => {
        if (res.success) {
          // 开始排队
          msg.emit('router: refreshRoute', {
            routeName: 'DriverTab',
          });
          msg.emit('router: goToNext', {
            routeName: 'DriverMain',
          });
        } else {
          msg.emit('app:tip', { text: res.msg ? res.msg : '网络错误' });
        }
      });
  };

  // 头部
  itemHead = (text) => {
    return (
      <View style={style.itemHead}>
        <Text style={{ color: '#333232', fontSize: px2dp(32) }}>{text}</Text>
      </View>
    );
  };

  checkStatus = () => {
    let { transportStatus } = this.state.details;
    let state = {};
    state = {
      1: <Text style={{ color: fontColorDeepRed }}>未完成</Text>,
      2: <Text style={{ color: fontColorSecDeepGray }}>已完成</Text>,
    };
    return state[transportStatus];
  };

  // 运单
  waybillView = () => {
    // 1  货主端   2车主端  3 司机端
    const { details } = this.state;
    const { waybillNo } = details;
    return (
      <View style={[style.itemFrame, style.waybill]}>
        <View style={style.waybillHead}>
          <Text
            style={{
              color: '#9D9A95',
              fontSize: px2dp(24),
            }}
          >
            {`运单号：${waybillNo}`}
          </Text>
          {this.checkStatus()}
        </View>
      </View>
    );
  };

  // 货物类型
  goodsTypeView = () => {
    const { details, unitOptionsMap } = this.state;
    const { goodsName, packageName, weight, weightUnit } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('货物类型')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble
            lineData={[
              goodsName,
              packageName,
              `${weight}${unitOptionsMap[weightUnit]}`,
            ]}
          />
        </View>
      </View>
    );
  };

  // 运费
  waybillCostView = () => {
    const { details, unitOptionsMap } = this.state;
    const { freightConsignorPer, freightUnit, lossesAmount, lossesUnit } =
      details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('运费')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble
            lineData={[
              `运费：${freightConsignorPer}元 / ${
                freightUnit && unitOptionsMap[freightUnit]
              }`,
              `损耗费：${lossesAmount}元 / ${
                lossesUnit && unitOptionsMap[lossesUnit]
              }`,
            ]}
          />
        </View>
      </View>
    );
  };

  // 备注
  remakeView = () => {
    const { details } = this.state;
    const { transports } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('备注信息')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble lineData={[transports[0].remark]} />
        </View>
      </View>
    );
  };

  // 装卸信息
  waybillRouteView = () => {
    const { details } = this.state;
    const { roads } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('装卸信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {roads.map((r, index, arr) => {
            return (
              <WaybillLine
                key={r.id}
                sources={r}
                renderInfoItem={this._renderInfoItem}
                lineHeight={150}
                type={r.type}
                lineText={this.computeDistance(index, arr)}
                lineIsShow={index < roads.length - 1}
              />
            );
          })}
        </View>
      </View>
    );
  };

  _renderInfoItem = (item) => {
    const {
      type,
      province,
      addressDetails,
      city,
      district,
      linkMan,
      linkMobile,
      loadingEndTime,
      loadingStartTime,
    } = item;
    return (
      <View style={{ marginLeft: px2dp(20) }}>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <View style={{ flex: 1 }}>
            <Text
              style={{
                color: '#343332',
                fontSize: px2dp(32),
              }}
              numberOfLines={2}
              ellipsizeMode='tail'
            >
              {`${province}${city}${district}${addressDetails}`}
            </Text>
          </View>
          {linkMan != null && linkMan != '' && (
            <TouchableOpacity onPress={() => this.handleFunc(linkMobile)}>
              <Image
                style={{
                  width: px2dp(69),
                  height: px2dp(69),
                }}
                source={iconCirclePhoneGray}
                resizeMode='stretch'
              />
            </TouchableOpacity>
          )}
        </View>
        {linkMan != null && linkMan != '' && (
          <Text
            style={{
              marginTop: px2dp(10),
              color: '#666562',
              fontSize: px2dp(26),
            }}
          >
            {`联系人：${linkMan}`}
          </Text>
        )}
        {type === 1 && (
          <Text
            style={{
              marginTop: px2dp(10),
              color: '#666562',
              fontSize: px2dp(26),
            }}
          >
            {`${loadingStartTime} - ${loadingEndTime} 可装货`}
          </Text>
        )}
      </View>
    );
  };

  // 司机信息
  driverInfo = () => {
    const { details } = this.state;
    const { cars, drivers } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('司机信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {drivers.map((v) => {
            return (
              <TouchableOpacity
                key={v.id}
                onPress={() => this.getDriverDetail(v.driverId)}
              >
                <DriverInfoCard
                  isRight
                  type={1}
                  imgUrl={v.head}
                  name={v.name}
                  info={v}
                />
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
    );
  };

  // 车辆信息
  vehicleInfo = () => {
    const { details } = this.state;
    const { cars } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('车辆信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {cars.map((v) => {
            return (
              <TouchableOpacity
                key={v.carNo}
                onPress={() => this.carInfo(v.carNo)}
              >
                <DriverInfoCard
                  type={2}
                  imgUrl={v.head}
                  name={v.carNo}
                  info={v}
                />
              </TouchableOpacity>
            );
          })}
        </View>
      </View>
    );
  };

  // 货主信息
  cargOwnerInfo = () => {
    const { details } = this.state;
    const { supplyOwnerResponse } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('货主信息')}
        <View style={{ marginTop: px2dp(20) }}>
          <TouchableOpacity
            onPress={() => this.getSourceDetail()}
          >
            <DriverInfoCard
              isRight
              type={1}
              imgUrl={supplyOwnerResponse.head}
              name={supplyOwnerResponse.name}
              info={supplyOwnerResponse}
            />
          </TouchableOpacity>
        </View>
      </View>
    );
  };

  // 回单信息
  receiptInfoView = () => {
    const { details, imageSources } = this.state;
    const { ticks } = details;
    let images = ticks.filter((item) => item.fileUrl !== null);
    return (
      <View style={style.itemFrame}>
        {this.itemHead('回单信息')}
        <TouchableOpacity
          onPress={() => {
            if (imageSources.length > 0) {
              this.setState({ modalVisible: true });
            }
          }}
          style={style.receiptContainer}
        >
          <View style={{ flexDirection: 'row' }}>
            {images.length > 0 ? (
              ticks.map((item) => {
                return (
                  <Image
                    key={item.id}
                    style={{
                      width: px2dp(120),
                      height: px2dp(120),
                      marginRight: px2dp(20),
                    }}
                    source={{ uri: fileUrl + item.fileUrl }}
                    resizeMode='stretch'
                  />
                );
              })
            ) : (
              <View
                style={{
                  height: px2dp(120),
                  justifyContent: 'center',
                }}
              >
                <Text style={{ textAlign: 'center' }}>暂无回单信息</Text>
              </View>
            )}
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  // 计算距离
  computeDistance = (index, arr) => {
    if (index === arr.length - 1) {
      return;
    }
    let distance = _.getDistance(
      arr[index].lat,
      arr[index].lgt,
      arr[index + 1].lat,
      arr[index + 1].lgt,
    );
    return `${distance} km`;
  };

  handleFunc = (phone) => {
    if (!phone) return msg.emit('app:tip', { text: '联系电话无效' });
    const url = `tel:${phone}`;
    Linking.canOpenURL(url)
      .then((supported) => {
        if (!supported) {
          NativeModules.WindowModule.showWindow(
            {
              content: `您的设备不支持该功能，请手动拨打${phone}`,
              onlyRightBtn: '1',
            },
            (e) => {},
          );
          return;
        }
        return Linking.openURL(url);
      })
      .catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  };

  /**
   * 接口调用
   * @param businessNo
   */

  // 查询运单详情
  info = (businessNo, plat) => {
    api.supply.info({ businessNo, plat }).then((res) => {
      if (res.success) {
        const { ticks } = res.data;
        let newImageSources = [];
        if (ticks.length > 0) {
          ticks.forEach((image) => {
            newImageSources.push({
              url: image.fileUrl,
              adress: image.addr,
              type: image.type === 1 ? '装货单' : '卸货单',
            });
          });
        }
        this.setState({ imageSources: newImageSources });
        this.setState({ details: res.data });
      } else {
        msg.emit('router: back');
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取司机详情
  getDriverDetail = (driverId) => {
    api.supply.driverInfo({ driverId }).then((res) => {
      if (res.success) {
        let data = {
          head: res.data.head ? { uri: res.data.head } : null,
          name: res.data.name,
          mobile: res.data.mobile,
          joinTime: res.data.joinTime,
          driverAge: res.data.driverAge,
          wayBillCount: res.data.waybillCount,
        };
        msg.emit('router: goToNext', {
          routeName: 'DriverDetail',
          data: data,
          isDriver: true,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取货主详情
  getSourceDetail = () => {
    const { details } = this.state;
    const { supplyOwnerResponse } = details;
    api.supply.consignorDetail({ custId: supplyOwnerResponse.custId, orderId: details.orderId }).then((res) => {
      console.log(res);
      if (res.success) {
        msg.emit('router: goToNext', {
          routeName: 'DetailDriverDetail',
          data: res.data,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };

  // 获取车辆详情
  carInfo = (carNo) => {
    api.supply.carInfo({ carNo }).then((res) => {
      if (res.success) {
        let infoData = {
          vehiclePhoto: '',
          numberPlates: res.data.carNo, // 车牌号
          joinTime: res.data.joinTime, // 入住时间
          driveAge: res.data.carAge, // 驾龄
          vehicleModel: res.data.carType, // 车型
          vehicleLong: res.data.carLength, // 车长
          load: res.data.weight, // 载重
          ascriptionEnterprise: res.data.companyName, // 所属企业
          cooperateType: res.data.carCoop, // 合作类型
          obdStatus: res.data.obdStatus, // obd信息
          obdInfo: res.data.obdInfo, // obd信息
          vehicleEquipment: '', // 车载设备
        };
        msg.emit('router: goToNext', {
          routeName: 'VehicleInfo',
          infoData,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  };
}
const style = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  scrollMargin: {
    marginBottom: px2dp(170),
  },
  itemFrame: {
    marginBottom: px2dp(20),
    borderRadius: px2dp(16),
    backgroundColor: mainBgColorWhite,
    padding: px2dp(20),
  },
  waybill: {
    paddingTop: px2dp(30),
    paddingBottom: px2dp(30),
    marginTop: px2dp(20),
  },
  waybillHead: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  goodsInfo: {
    marginTop: px2dp(20),
  },
  itemHead: {
    justifyContent: 'center',
    paddingBottom: px2dp(15),
    borderBottomWidth: px2dp(1),
    borderBottomColor: splitLineColorLightGray,
  },
  receiptContainer: {
    marginTop: px2dp(20),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  botTab: {
    // position: 'absolute',
    bottom: 0,
    left: 0,
    width: screenWidth,
    height: px2dp(168),
    flexDirection: 'row',
    backgroundColor: '#fff',
    padding: 16,
    borderTopColor: '#e4e4e2',
    borderWidth: px2dp(0.5),
  },
});
